import {
  setGoodsInfo,
  getGoodsInfo,
  setGoodsPriceTotal,
  setGoodsCountTotal,
  getGoodsPriceTotal,
  getGoodsCountTotal
} from '@/common/storage.js'
export default {
  namespaced: true,
  state: {
    // 保存商品的相关信息 goods_id goods_name goods_price goods_image goods_total goods_status
    goodsInfo: JSON.parse(getGoodsInfo() || '[]'),
    priceAll: getGoodsPriceTotal() || 0,
    countAll: getGoodsCountTotal() || 0,
  },
  mutations: {
    // 更新商品信息
    updateGoodsInfo(state, goods) {
      // 如果用户添加的是一款商品，则只需要进行数量的添加
      const good = state.goodsInfo.find(item => item['goods_id'] === goods.goods_id)
      if (!good) {
        // 添加新商品
        state.goodsInfo.push({
          goods_id: goods.goods_id,
          goods_name: goods.goods_name,
          goods_price: goods.goods_price,
          goods_small_logo: goods.goods_small_logo,
          goods_total: 1,
          goods_status: true
        })
      } else {
        good['goods_total'] += 1
      }
      this.commit('goodsCar/updateGoodsPriceTotal')
      this.commit('goodsCar/updateGoodsCountTotal')
      setGoodsInfo(state.goodsInfo)
    },
    // 修改商品选中状态和数量 goods={goods_id,goods_status}
    updateGoodsStatus(state, goods) {
      // 获取存在vuex中的商品信息对象
      const good = state.goodsInfo.find(item => item.goods_id === goods.goods_id)
      if (good) {
        if (goods.hasOwnProperty('goods_status')) {
          // 修改商品的状态
          good.goods_status = goods.goods_status
        } else if (goods.hasOwnProperty('goods_total')) {
          // 修改商品的数量
          good.goods_total = goods.goods_total
        }
        this.commit('goodsCar/updateGoodsPriceTotal')
        this.commit('goodsCar/updateGoodsCountTotal')
        // 本地化存储      
        setGoodsInfo(state.goodsInfo)
      }
    },
    // 删除商品
    delGoods(state, goods) {
      state.goodsInfo = state.goodsInfo.filter(item => item.goods_id !== goods.goods_id)
      // 删除完商品之后需要将商品数量和商品总价格进行改变 
      this.commit('goodsCar/updateGoodsPriceTotal')
      this.commit('goodsCar/updateGoodsCountTotal')
      // 本地化存储
      setGoodsInfo(state.goodsInfo)
    },
    // 获取所选中的商品价格的总和
    updateGoodsPriceTotal(state) {
      state.priceAll = state.goodsInfo.filter(item => item.goods_status === true).reduce((total, obj) => total += obj
        .goods_total * obj.goods_price, 0).toFixed(2)
      // 本地持久化存储
      setGoodsPriceTotal(state.priceAll)
    },
    // 获取所选择的商品数量总和
    updateGoodsCountTotal(state) {
      state.countAll = state.goodsInfo.filter(item => item.goods_status === true).reduce((total, obj) => total += obj
        .goods_total, 0)
      // 本地持久化存储
      setGoodsCountTotal(state.countAll)
    },
    // 点击全选，修改所有商品的选中状态
    updateAllGoodsStatus(state,status){
      state.goodsInfo.forEach(item => {item.goods_status = status})
      setGoodsInfo(state.goodsInfo)
      this.commit('goodsCar/updateGoodsPriceTotal')
      this.commit('goodsCar/updateGoodsCountTotal')
    }
  }
}
